﻿using System;
using System.Web;

using Eneta.Portal.Common.Loggers;

namespace Eneta.Portal.Common
{
    /// <summary>
    /// Wrapper class for loggers. The methods of this class are actually called from code. The class 
    /// gets current logger from resolver and calls wrapped methods on it.
    /// </summary>
    public static class Logger
    {
        /// <summary>
        /// Logs the informative message.
        /// </summary>
        /// <param name="message">The message to log.</param>
        /// <param name="source">The source of message.</param>
        public static void LogInfo(string message, string source)
        {
            CurrentLogger.LogInfo(message, source);
        }

        /// <summary>
        /// Logs the given warning.
        /// </summary>
        /// <param name="message">The message to log.</param>
        /// <param name="source">The source of message.</param>
        public static void LogWarning(string message, string source)
        {
            CurrentLogger.LogWarning(message, source);
        }

        /// <summary>
        /// Logs the given exception.
        /// </summary>
        /// <param name="ex">The exception to log.</param>
        public static void LogException(Exception ex)
        {
            CurrentLogger.LogException(ex);
        }

        private static ILogger CurrentLogger
        {
            get
            {
                var context = HttpContext.Current;
                ILogger logger;
                if (context != null)
                {
                    logger = context.Items["Logger"] as ILogger;
                    if (logger != null)
                        return logger;
                }

                try
                {
                    logger = Resolver.Resolve<ILogger>();
                }
                catch(Exception ex)
                {
                    // Resolver was not able to create logger for us. By default we will use ULS logger
                    // because it needs no additional configuration options set by user.
                    logger = new UlsLogger();
                    logger.LogWarning("Cannot create file logger. Switching to ULS logger instead", "Logger");
                    logger.LogException(ex);
                }

                if(context != null)
                    context.Items["Logger"] = logger;

                return logger;
            }
        }
    }
}
